package com.sniff.atp.utils;

import com.github.crab2died.ExcelUtils;
import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvValidationException;
import org.apache.commons.io.FileUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.yaml.snakeyaml.Yaml;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @BelongsProject: sniff-atp
 * @Author: ljj
 * @CreateTime: 2022/11/9 17:03
 * @Description:
 * @Version: 1.0
 */
public class FileUtil {


    private FileUtil(){}

    /**
     * 获取json/txt/text文件内容返回字符串
     * @param path
     * @return
     * @throws IOException
     */
    public static String readFileToString(String path) throws IOException {
        File file = new File(path);
        return FileUtils.readFileToString(file, StandardCharsets.UTF_8);
    }
    /**
     * 读取excel返回成List(更多方法请详见ExcelUtils类)
     * @param path
     * @throws Exception
     */
    public static List<List<String>> readExcelToList(String path) throws IOException, InvalidFormatException {
        return ExcelUtils.getInstance().readExcel2List(path);
    }
    /**
     * 读取csv文件返回成List
     * @param path
     * @throws Exception
     */
    public static List<List<String>> readCsvToList(String path) throws CsvValidationException, IOException {
        List<String[]> csvArayy = readCsvToListArray(path);
        List<List<String>> csvList = new ArrayList<>();
        for (int i=0;i<csvArayy.size();i++){
            csvList.add(Arrays.asList(csvArayy.get(i)));
        }
        return csvList;
    }
    /**
     * 读取csv文件返回成数组List
     * @param path
     * @throws Exception
     */
    public static List<String[]> readCsvToListArray(String path) throws IOException, CsvValidationException {
        File file  = new File(path);
        CSVReader reader = new CSVReader(new InputStreamReader(Files.newInputStream(file.toPath()), StandardCharsets.UTF_8));

        List<String[]> csvArayy = new ArrayList<>();
        try {
            reader.readNext();
            String[] csvRow = null;
            while ((csvRow = reader.readNext()) != null) {
                csvArayy.add((csvRow));
            }
        }finally {
            reader.close();
        }
        return csvArayy;
    }

    /**
     * 加载yml配置文件
     * @return
     * @throws FileNotFoundException
     */
    public static Map<String,Object> loadYml(String path) throws FileNotFoundException {
        Map<String,Object> map = null;
        try {
            Yaml yaml = new Yaml();
            InputStream inputStream = new FileInputStream(path);
            map = yaml.load(inputStream);
        }catch (FileNotFoundException e) {
            throw new FileNotFoundException("配置文件路径错误:"+e.getMessage());
        }
        return map;
    }
}
